﻿using System.Collections.Generic;
using System.Linq;
using MRGSP.SurveyMaster.Core.Model;
using MRGSP.SurveyMaster.Core.Service.Utils;

namespace MRGSP.SurveyMaster.Service.Utils
{
    public class QuestionValidator : IQuestionValidator
    {
        public IEnumerable<ValidationMessage> Validate(Question question, IEnumerable<Answer> answers)
        {
            if (!question.Mandatory) yield break;
            if (!question.HasChildren()) yield break;
            if (question.HasParent() && !answers.Select(o => o.QuestionId).Contains(question.Id)) yield break;

            if (answers.Select(o => o.QuestionId).Intersect(question.Children.Select(o => o.Id)).Count() == 0)
                yield return
                    new ValidationMessage { QuestionId = question.Id, Message = string.Format("Question {0} is mandatory ", question.Text) };

            foreach (var message in question.Children.SelectMany(child => Validate(child, answers)))
                yield return message;
        }
    }
}